package com.ruoyi.tzai.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.HashMap;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.tzai.domain.UserFavorite;
import com.ruoyi.tzai.domain.NewsArticle;
import com.ruoyi.tzai.service.IUserFavoriteService;
import com.ruoyi.tzai.service.INewsArticleService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * 用户收藏Controller
 *
 * @author tzai
 * @date 2025-10-27
 */
@Api(tags = "用户收藏管理")
@RestController
@RequestMapping("/tzai/favorite")
public class UserFavoriteController extends BaseController
{
    @Autowired
    private IUserFavoriteService userFavoriteService;

    @Autowired
    private INewsArticleService newsArticleService;

    /**
     * 查询用户收藏列表（包含文章信息）
     */
    @ApiOperation("查询用户收藏列表")
    @PreAuthorize("@ss.hasPermi('tzai:favorite:list')")
    @GetMapping("/list")
    public TableDataInfo list(UserFavorite userFavorite)
    {
        // 从token获取当前用户ID，只查询当前用户的收藏
        Long userId = getUserId();
        userFavorite.setUserId(userId);
        startPage();
        List<UserFavorite> favoriteList = userFavoriteService.selectUserFavoriteList(userFavorite);

        // 关联查询文章信息
        List<Map<String, Object>> resultList = new ArrayList<>();
        for (UserFavorite favorite : favoriteList) {
            NewsArticle article = newsArticleService.selectNewsArticleByArticleId(favorite.getArticleId());
            if (article != null) {
                Map<String, Object> item = new HashMap<>();
                // 将文章信息转换为Map
                item.put("articleId", article.getArticleId());
                item.put("title", article.getTitle());
                item.put("content", article.getContent());
                item.put("source", article.getSource());
                item.put("url", article.getSourceUrl()); // 后端字段是sourceUrl，映射为url供前端使用
                item.put("articleType", article.getArticleType());
                item.put("companyId", article.getCompanyId());
                item.put("companyCode", article.getCompanyCode());
                item.put("companyNameCn", article.getCompanyNameCn());
                item.put("publishTime", article.getPublishTime());
                item.put("status", article.getStatus());
                item.put("createTime", article.getCreateTime());
                item.put("updateTime", article.getUpdateTime());
                item.put("isFavorite", true); // 收藏列表中的都是已收藏
                resultList.add(item);
            }
        }

        return getDataTable(resultList);
    }

    /**
     * 导出用户收藏列表
     */
    @ApiOperation("导出用户收藏列表")
    @PreAuthorize("@ss.hasPermi('tzai:favorite:export')")
    @Log(title = "用户收藏", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, UserFavorite userFavorite)
    {
        Long userId = getUserId();
        userFavorite.setUserId(userId);
        List<UserFavorite> list = userFavoriteService.selectUserFavoriteList(userFavorite);
        ExcelUtil<UserFavorite> util = new ExcelUtil<UserFavorite>(UserFavorite.class);
        util.exportExcel(response, list, "用户收藏数据");
    }

    /**
     * 获取用户收藏详细信息
     */
    @ApiOperation("获取用户收藏详细信息")
    @PreAuthorize("@ss.hasPermi('tzai:favorite:query')")
    @GetMapping(value = "/{favoriteId}")
    public AjaxResult getInfo(@PathVariable("favoriteId") Long favoriteId)
    {
        return success(userFavoriteService.selectUserFavoriteByFavoriteId(favoriteId));
    }

    /**
     * 检查是否已收藏
     */
    @ApiOperation("检查是否已收藏")
    @GetMapping(value = "/check")
    public AjaxResult checkFavorite(@RequestParam Long articleId)
    {
        Long userId = getUserId();
        UserFavorite favorite = userFavoriteService.selectUserFavoriteByUserIdAndArticleId(userId, articleId);
        return success(favorite != null);
    }

    /**
     * 新增用户收藏
     */
    @ApiOperation("新增用户收藏")
    @PreAuthorize("@ss.hasPermi('tzai:favorite:add')")
    @Log(title = "用户收藏", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody UserFavorite userFavorite)
    {
        // 从token获取当前用户ID
        Long userId = getUserId();
        userFavorite.setUserId(userId);
        return toAjax(userFavoriteService.insertUserFavorite(userFavorite));
    }

    /**
     * 删除用户收藏
     */
    @ApiOperation("删除用户收藏")
    @PreAuthorize("@ss.hasPermi('tzai:favorite:remove')")
    @Log(title = "用户收藏", businessType = BusinessType.DELETE)
    @DeleteMapping("/{favoriteIds}")
    public AjaxResult remove(@PathVariable Long[] favoriteIds)
    {
        return toAjax(userFavoriteService.deleteUserFavoriteByFavoriteIds(favoriteIds));
    }

    /**
     * 切换收藏状态（收藏/取消收藏）
     */
    @ApiOperation("切换收藏状态")
    @Log(title = "用户收藏", businessType = BusinessType.UPDATE)
    @PostMapping("/toggle")
    public AjaxResult toggle(@RequestParam Long articleId)
    {
        Long userId = getUserId();
        boolean isFavorited = userFavoriteService.toggleFavorite(userId, articleId);
        AjaxResult result = success(isFavorited ? "已收藏" : "已取消收藏");
        result.put("isFavorited", isFavorited);
        return result;
    }
}
